package com.lock.agency;

import com.lock.annotation.ZKLock;
import com.lock.util.OrderLockUtil;
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 给main类测试用，已启用注解aop的形式，见baseTest类
 * Created by hx on 2017/7/17.
 */
public class MyOrderLockInvocationHandler implements InvocationHandler{
    //目标对象
    private Object target;

    public MyOrderLockInvocationHandler(){}

    public MyOrderLockInvocationHandler(Object target) {
        this.target = target;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        OrderLockUtil orderLockUtil = new OrderLockUtil();
        Object result = null;
        if (method.isAnnotationPresent(ZKLock.class)) {
            if (orderLockUtil.entrance()) {
                result = method.invoke(target, args);   //业务方法执行
                orderLockUtil.deleteLock();
            }
        } else {
            result = method.invoke(target, args);   //业务方法执行
        }
        return result;
    }

    public Object getProxy(){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }
}
